﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Collections;

namespace NJL.WebUsers.Visitor
{
    public partial class TravelsDetails : BasePageVisitor
    {
        private readonly NJL.BLL.NJL_USER bllUser = new BLL.NJL_USER();
        private readonly NJL.BLL.NJL_PERSON bllPerson = new BLL.NJL_PERSON();
        private readonly NJL.BLL.NJL_NEWS bll = new BLL.NJL_NEWS();
        private readonly NJL.BLL.NJL_CS_NEWS_TYPE bllNewsType = new BLL.NJL_CS_NEWS_TYPE();
        private readonly NJL.BLL.NJL_NEWS_COMMENT bllComment = new BLL.NJL_NEWS_COMMENT();
        private readonly NJL.BLL.NJL_ATTRACTION bllAttr = new BLL.NJL_ATTRACTION();
        private readonly NJL.BLL.NJL_COMPANY bllCompany = new BLL.NJL_COMPANY();
        
        protected NJL.Model.NJL_NEWS model;
        protected NJL.Model.NJL_NEWS_COMMENT modelComment;
        protected NJL.Model.NJL_USER modelUser = new Model.NJL_USER();
        protected NJL.Model.NJL_PERSON modelPerson;

        protected IList<Model.NJL_ATTRACTION> LIST_ATTRACTION;
        protected IList<Model.NJL_COMPANY> LIST_COMPANY;
        protected ArrayList ArrayListTags = new ArrayList();


        protected void Page_Load(object sender, EventArgs e)
        {
            //处理标签，并获取与标签有关的景点和农家乐信息
            model = bll.GetModel(Request.QueryString["id"]);
            char[] chars = { ',', '，' };
            string[] strsTag = model.NEWS_TAG.Split(chars);
            for (int i = 0; i < strsTag.Length; i++)
            {
                ArrayListTags.Add(strsTag[i]);
            }
            string strWhereAttraction = "";
            string strWhereCompany = "";
            if (strsTag.Length > 0)
            {
                strWhereAttraction = "(";
                for (int i = 0; i < strsTag.Length; i++)
                {
                    if (i == 0)
                    {
                        strWhereAttraction += " ATTRACTION_TAG like '%" + strsTag[i] + "%'";
                    }
                    else
                    {
                        strWhereAttraction += " or ATTRACTION_TAG like '%" + strsTag[i] + "%'";
                    }
                }
                strWhereAttraction += ")";
                LIST_ATTRACTION = bllAttr.GetModelList(4, " NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' AND " + strWhereAttraction, "VISIT_COUNT DESC");
                if (LIST_ATTRACTION.Count == 0)
                {
                    LIST_ATTRACTION = bllAttr.GetModelList(4, " NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' ", "VISIT_COUNT DESC");
                }

                //企业
                strWhereCompany = "(";
                for (int i = 0; i < strsTag.Length; i++)
                {
                    if (i == 0)
                    {
                        strWhereCompany += " NJL_COMPANY_SERVICE.TAG like '%" + strsTag[i] + "%'";
                    }
                    else
                    {
                        strWhereCompany += " or NJL_COMPANY_SERVICE.TAG like '%" + strsTag[i] + "%'";
                    }
                }
                strWhereCompany += ")";

                strWhereCompany = "NJL_COMPANY.ID IN (SELECT NJL_COMPANY_ID FROM NJL_COMPANY_SERVICE WHERE NJL_COMPANY_ID IN (SELECT ID FROM NJL_COMPANY WHERE NJL_SYS_BASE_ID='" + WEBSITE_CODE + "') AND " + strWhereCompany + " )";

                LIST_COMPANY = bllCompany.GetModelList(4, " NJL_COMPANY.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' AND " + strWhereCompany, "NJL_COMPANY.VISIT_COUNT DESC");

                if (LIST_COMPANY.Count == 0)
                {
                    LIST_COMPANY = bllCompany.GetModelList(4, " NJL_COMPANY.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "'", "NJL_COMPANY.VISIT_COUNT DESC");
                }
            }
            else
            {
                //
                LIST_ATTRACTION = bllAttr.GetModelList(4, " NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' ", "VISIT_COUNT DESC");
                LIST_COMPANY = bllCompany.GetModelList(4, " NJL_COMPANY.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "'", "NJL_COMPANY.VISIT_COUNT DESC");
            }
            if (!IsPostBack)
            {               
                LoadPageSEO();
                bind();
            }         
        
        }
        void bind()
        {
            model = bll.GetModel(Request.QueryString["id"]);
            litdate.Text = string.Format("{0:yyyy-MM-dd}", model.CREATE_DATE_TIME);
            litContent.Text = model.NEWS_CONTECT;
            litHit.Text = model.VISIT_COUNT.ToString();
            if (model.NEWS_TITLE.Length > 30)
            {
                litTitle.Text = model.NEWS_TITLE.Substring(0, 30);
            }
            else
            {
                litTitle.Text = model.NEWS_TITLE;
            }
            if (model.IMAGE_CODE != "")
            {
                Image1.ImageUrl = BasePage.GetImageUrl(model.IMAGE_CODE, "5");
            }
            else
            {
                Image1.Visible = false;
            }
            #region 点击次数
            bll.updateHitandDate(Request.QueryString["id"]);
            #endregion
            object obj = bll.GetNextNewsId(Request.QueryString["id"].ToString(), Request.QueryString["uid"].ToString());
            if (obj != null)
            {
                hplinkNext.NavigateUrl = "/wanjia/" + Request.QueryString["uid"] + "-youji-" + obj.ToString() + ".html";
                model = bll.GetModel(obj.ToString());
                hplinkNext.Text = model.NEWS_TITLE;
            }
            else
            {
                hplinkNext.Text = "已经是第一篇了";
                hplinkNext.Enabled = false;
            }
            Object objPrev = bll.GetPrevNewsId(Request.QueryString["id"].ToString(), Request.QueryString["uid"].ToString());
            if (objPrev != null)
            {
                hipLinkPrev.NavigateUrl = "/wanjia/" + Request.QueryString["uid"] + "-youji-" + objPrev.ToString() + ".html";
                model = bll.GetModel(objPrev.ToString());
                hipLinkPrev.Text = model.NEWS_TITLE;
            }
            else
            {
                hipLinkPrev.Text = "已经是最后一篇了";
                hipLinkPrev.Enabled = false;
            }

            DataSet ds = bllComment.GetList("NJL_NEWS_ID='" + Request.QueryString["id"].ToString() + "'");
            string[] parameters = { "id", "uid" };
            rptCommentList.DataSource = ds;
            rptCommentList.DataBind();
         
            #region 新闻分类
            ds = bllNewsType.GetList("TYPE_CODE<100");
            newsType.DataSource = ds;
            newsType.DataBind();
            #endregion
            #region 评论最多文章
            DataSet dsTravel = bll.GetList(4, "NJL_PERSON_ID='" + Request.QueryString["uid"] + "'", "COMMENT_COUNT desc,ID desc");
            rptCommentMax.DataSource = dsTravel;
            rptCommentMax.DataBind();
            #endregion
            #region 全部新闻
            ds = bll.GetList("NJL_PERSON_ID='" + Request.QueryString["uid"] + "'");
            litAllNews.Text = ds.Tables[0].Rows.Count.ToString();
            #endregion


          
        }
        /// <summary>
        /// 加载页面SEO
        /// </summary>
        private void LoadPageSEO()
        {
            modelUser = bllUser.GetModel(Request.QueryString["uid"]);
            model = bll.GetModel(Request.QueryString["id"].ToString());
            Page.Title = model.NEWS_TITLE + "-" + modelUser.USER_NAME+"的乡间小屋";
            HtmlMeta myMeta = new HtmlMeta();
            myMeta.Name = "Keywords";
            myMeta.Content = model.NEWS_TAG;
            this.Header.Controls.Add(myMeta);

            HtmlMeta myMeta1 = new HtmlMeta();
            myMeta1.Name = "Description";
            myMeta1.Content = model.NEWS_SUBJECT_TITLE;
            this.Header.Controls.Add(myMeta1);
        }
        protected void btnComment_Click(object sender, EventArgs e)
        {

            if (UserId == "" || UserType == "-1")
            {
                Royalsoft.Common.MessageBox.ShowAndRedirect(this, "请登录后再发表", "/Login.aspx?url=" + Server.UrlEncode(Request.RawUrl.ToString()));
                return;
            }
            else
            {
                if (Session["CheckCode"] != null)
                {
                    if (txtValidate.Text.Trim().ToLower() != Session["CheckCode"].ToString().ToLower())
                    {
                        Royalsoft.Common.MessageBox.Show(this, "请输入正确的验证码");
                        return;
                    }
                    modelComment = new Model.NJL_NEWS_COMMENT();
                    modelComment.ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                    modelComment.NEWS_COMMENT = txtComment.Text.Trim();
                    modelComment.CREATE_USER_ID = new BasePage().UserId;
                    modelComment.CREATE_USER_NAME = new BasePage().UserName;
                    modelComment.CREATE_DATE_TIME = DateTime.Now;
                    modelComment.NJL_NEWS_ID = Request.QueryString["id"].ToString();
                    if (bllComment.Add(modelComment))
                    {
                        string message;
                        if (HandleIntegral(UserId, "3", out message))
                        {

                        }
                        Royalsoft.Common.MessageBox.ShowAndRedirect(this, "评论成功+2分", Request.RawUrl);
                        if (bll.updateCommentHitAndDate(Request.QueryString["id"]))
                        {

                        }
                    }
                }
                else
                {
                    Royalsoft.Common.MessageBox.ShowAndRedirect(this, "连接系统超时", "" + Request.RawUrl);
                }
            }
        }
        protected void rptCommentList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView grv = (DataRowView)e.Item.DataItem;
                string userId = grv["CREATE_USER_ID"].ToString();
                Image imgUserHead = e.Item.FindControl("imgUserHead") as Image;
                modelPerson = bllPerson.GetModelByUserId(userId);
                if (modelPerson != null)
                {
                    if (modelPerson.IMAGE_CODE != "")
                    {
                        imgUserHead.ImageUrl = GetImageUrl(modelPerson.IMAGE_CODE, "U1");
                        imgUserHead.BorderWidth = 1;
                    }
                    else
                    {
                        imgUserHead.ImageUrl = "/Images/avatar.jpg";
                        imgUserHead.BorderWidth = 1;
                    }
                }
                LinkButton lbtn = e.Item.FindControl("lbtnDel") as LinkButton;
                if (UserId != "" && UserId.Equals(Request.QueryString["uid"]))
                {
                    lbtn.Visible = true;
                }
                else
                {
                    lbtn.Visible = false;
                }

            }
        }

        protected void rptCommentList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                string id = e.CommandArgument.ToString();
                if (bllComment.Delete(id))
                {
                    bind();
                }
                else
                {
                    Royalsoft.Common.MessageBox.Show(this, "删除失败");
                }
            }
        }
        DataSet ds;
        protected void newsType_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView grv = (DataRowView)e.Item.DataItem;
                string typeCode = grv["TYPE_CODE"].ToString();
                Literal lit = e.Item.FindControl("litNewsCount") as Literal;
                ds = bll.GetList("NJL_PERSON_ID='" + Request.QueryString["uid"] + "' and TYPE_CODE='" + typeCode + "'");
                lit.Text = ds.Tables[0].Rows.Count.ToString();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect("/SearchTopics.aspx?keywords=" + keywords.Value);
        }
    }
}